<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>{{ runnerData.name }}</span>
    </div>
    <div class="flex">
      <div class="">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane :label="item.name" :name="k + ''" v-for="(item, k) in tableData" :key="k"></el-tab-pane>
        </el-tabs>
        <div class="canvas_wrap">
          <el-card class="box-card">
            <div slot="header" class="clearfix"><span>动作总体范围展示</span></div>
            <div class="ruler-wrap" id="ruler"></div>
            <div style="display: flex;">
              <div id="mountNode" style="flex: 1;" @mouseout="mouseout" @mouseleave="mouseleave"></div>
            </div>
          </el-card>
          <el-card class="box-card">
            <div slot="header" class="clearfix"><span>跟机展示</span></div>
            <div style="display: flex;">
              <div id="followMount" style="flex: 1;"></div>
            </div>
          </el-card>

          <!-- 固定域 -->
          <div class="flex js_sb flex_center">
            <el-tabs v-model="tabValue" style="width: 600px;" type="card" @tab-click="tabsClick" editable
              @edit="handleTabsEdit">
              <el-tab-pane v-for="(item, index) in fixedList" :key="index" :label="'固定域:' + item.loc"
                :name="index + ''"></el-tab-pane>
            </el-tabs>
          </div>
          <div class="ruler-wrap" id="ruler2"></div>
          <div style="display: flex;" @mouseout="fixedmouseout" @mouseleave="fixedmouseleave">
            <div style="flex: 1;" id="fixedMount"></div>
          </div>
        </div>
      </div>
      <div class="" style="margin-left: 12px;">
        <el-card class="box-card">
          <div slot="header" class="clearfix"><span>关联煤机执行动作</span></div>
          <el-collapse v-model="activeName" accordion>
            <template v-for="item in tableData">
              <el-collapse-item :title="item.name" :name="item.id">
                <!--  <draggable v-model="item.actions" chosenClass="chosen" forceFallback="true" animation="1000"
                  @start="sortStart" @end="sortEnd"> -->
                <transition-group class="flex flex_center flex_wrap">
                  <div class="actions_item" v-for="(item,i) in item.actions" :key="i">
                    {{ item.name }}
                  </div>
                  <template v-for="(item,i) in fixedList">
                    <div class="actions_item" v-for="(key,k) in item.items" :key="k">
                      {{ key.name }}
                    </div>
                  </template>
                </transition-group>
                <!-- </draggable> -->
              </el-collapse-item>
            </template>

          </el-collapse>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix"><span>动作属性配置</span></div>
          <div>{{ form.actionName }}</div>
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="调试顺序">
              <el-select v-model="form.OrderType" size="mini" placeholder="请选择活动区域">
                <el-option v-for="item in enSTrackActOrder" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="触发模式">
              <el-select v-model="form.TriggerMode" size="mini" placeholder="请选择活动区域">
                <el-option v-for="item in enShearerActTriggerMode" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="触发煤机位置">
              <el-input v-model="form.ShearerLoc" size="mini"></el-input>
            </el-form-item>
            <el-form-item label="触发煤机方向" v-if="form.ShearerLoc != 0 && form.ShearerLoc">
              <el-select v-model="form.ShearerDir" size="mini" placeholder="请选择活动区域">
                <el-option v-for="item in enSTrackRunDir" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="有效区间L">
              <el-input v-model.number="form.ActRegionL" size="mini"></el-input>
            </el-form-item>
            <el-form-item label="有效区间H">
              <el-input v-model.number="form.ActRegionH" size="mini"></el-input>
            </el-form-item>
            <el-form-item label="参数组">
              <el-select v-model="form.ParaIDs" multiple size="mini" placeholder="请选择活动区域">
                <el-option v-for="item in enParaID" :key="item.key" :label="item.name" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="随动距离" v-if="!isActionBlock">
              <el-input-number v-model="form._SDLength" controls-position="right"></el-input-number>
            </el-form-item>
            <el-form-item label="随动范围" v-if="!isActionBlock">
              <el-input-number v-model="form._SDScope" controls-position="right"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">更新</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
    <div style="width: 100%;height: 200px;"></div>
    <el-card class="box-card actionsPool">
      <div slot="header" class="clearfix"><span>动作池</span></div>
      <div class="flex">
        <draggable v-model="actions" chosenClass="chosen" forceFallback="true" animation="1000" @start="onStart"
          @end="onEnd">
          <transition-group class="flex flex_center flex_wrap" style="max-height: 80px;overflow-y: scroll;">
            <el-tooltip v-for="item in actions" :key="item.STrackID" effect="dark" placement="top-start">
              <div slot="content">
                <p>{{ '有效区间L:' + item.ActRegionL + ';有效区间H:' + item.ActRegionH }}</p>
                <p v-if="item.ShearerDir == 1">触发方向:下行</p>
                <p v-else-if="item.ShearerDir == 2">触发方向:上行</p>
                <p v-else-if="item.ShearerDir == 0">触发方向:即时</p>
              </div>
              <div class="actions_item" :class="item.RegionType != 0 ? '' : 'bg_reginType'">{{ item.name }}</div>
            </el-tooltip>
          </transition-group>
        </draggable>
      </div>
    </el-card>
  </el-card>
</template>

<script>
  import initX6 from './utils/initX6.js';
  import InDB from "./utils/initDB.js"
  import colors from "./utils/colors.js"
  import draggable from 'vuedraggable';
  import enSTrackActOrder from './data/enSTrackActOrder';
  import enShearerActTriggerMode from './data/enShearerActTriggerMode';
  import enParaID from './data/enParaID';
  import enSTrackRunDir from './data/enSTrackRunDir';
  import formData from './utils/formdata.js';
  import rule from './utils/rule.js';

  export default {
    components: {
      draggable
    },
    data() {
      return {
        step: 2,
        enSTrackRunDir: enSTrackRunDir,
        enParaID: enParaID,
        enSTrackActOrder: enSTrackActOrder,
        enShearerActTriggerMode: enShearerActTriggerMode,
        mountGraph: null,
        followGraph: null,
        fixedGraph: null,
        tableData: [],
        actions: [],
        form: {},
        activeName: 0,
        collapseName: '1',
        tabValue: '0',
        isActionBlock: false,
        isTrack: false,
        isFixed: false,
        fixedTrack: {
          source: "mount",
          hierarchy: 0
        },
        runnerData: {},
        fixedList: []
      };
    },
    methods: {
      sortEnd() {},
      sortStart() {},
      fixedmouseout() {
        this.isFixed = true;
      },
      fixedmouseleave() {
        this.isFixed = false;
      },
      onSubmit() {
        if (this.isActionBlock) {
          let temp
          let tableItem = this.tableData[this.activeName].fixedList[this.tabValue]
          for (let i = 0; i < tableItem.items.length; i++) {
            let item = tableItem.items[i]
            if (item.ShearerLoc != tableItem.loc) {
              let obj = {
                loc: item.ShearerLoc || 0,
                items: []
              }
              this.tableData[this.activeName].fixedList.push(obj)
              tableItem.items.splice(i, 1)
              break
            }
          }
          InDB.actionsPool.put({
            ...this.form
          })
          this.updateFixedMount()
        }
        if (!this.isActionBlock) {
          InDB.actionsPool.put({
            ...this.form
          })
          this.updateMount();
        }
      },
      handleClickPrint() {
        console.log(this.tableData);
      },
      mouseout() {
        this.isTrack = true;
        // console.log(111);
      },
      mouseleave() {
        this.isTrack = false;
        // console.log(222);
      },
      onStart() {},
      onEnd(e) {
        let index = e.oldIndex;
        let tableItem = this.tableData[this.activeName]
        if (!this.isTrack) {


          if (this.actions[index].RegionType != 0) {
            this.$notify({
              title: '警告',
              message: '所选动作不支持此调度区域',
              type: 'warning'
            });
            return
          }
          if (this.actions[index].ShearerDir == 0) {

          }
          if (this.actions[index].ShearerDir != tableItem.TriggerDir) {
            this.$notify({
              title: '警告',
              message: '所选动作不支持此煤机触发方向',
              type: 'warning'
            });
            return
          }
          if (this.fixedList.length < 1) {
            let obj = {
              loc: this.actions[index].ShearerLoc || 0,
              items: [{
                ...this.actions[index],
                PreRunnerID: "mount",
                hierarchy: 1
              }]
            }
            this.fixedList.push(obj)
            this.updateFixedMount()
            return
          }
          let checkoutNode = tableItem.fixedList[this.tabValue].items.some(item => {
            return item.id = this.actions[index].id
          })
          if (checkoutNode) {
            this.$notify({
              title: '警告',
              message: '所选动作重复',
              type: 'warning'
            });
            return
          }

          if (this.actions[index].ShearerLoc == 0) {
            console.log('ShearerLoc', 0);
            let obj = {
              loc: this.actions[index].ShearerLoc || 0,
              items: []
            }
            this.fixedList.push(obj)
            return
          }
          if (this.fixedList[this.tabValue].loc != 0 && this.actions[index].ShearerLoc != tableItem.fixedList[this
              .tabValue].loc) {
            let obj = {
              loc: this.actions[index].ShearerLoc || 0,
              items: []
            }
            this.fixedList.push(obj)
            return
          }

          let item = {
            ...this.actions[index],
            PreRunnerID: this.fixedTrack.source,
            hierarchy: this.fixedTrack.hierarchy + 1
          };
          this.fixedList[this.tabValue].items.push(item);
          this.fixedList[this.tabValue].loc = this.actions[index].ShearerLoc
          this.updateFixedMount();
          return
        }
        if (this.isTrack) {
          if (this.actions[index].RegionType != 0) {
            console.log(tableItem);
            let checkoutActions = tableItem.actions.some(item => {
              return item.STrackID == this.actions[index].STrackID
            })
            if (checkoutActions) {
              return
            }
            tableItem.actions.push(this.actions[index]);
            this.updateMount();
          }
        }
      },

      tabsClick() {
        this.updateFixedMount()

      },
      handleTabsEdit(targetName, action) {
        let tableItem = this.tableData[this.activeName]
        if (action == 'add') {
          let obj = {
            loc: 0,
            items: []
          };
          tableItem.fixedList.push(obj);
          return;
        }
        if (action == 'remove') {
          tableItem.fixedList.splice(targetName, 1);
          return;
        }
      },
      handleClick(tab, event) {
        this.activeName = tab.name;
        this.fixedList = this.tableData[this.activeName].fixedList
        this.updateMount();
      },

      initFixedMount() {
        this.fixedGraph = initX6.initMount({
          node: 'fixedMount',
          scroller: true,
          size: 16
        });
        this.fixedGraph.on('node:mouseenter', ({
          node
        }) => {
          if (node.id == "mount") {
            let obj = {
              source: "mount",
              hierarchy: 0
            };
            this.fixedTrack = obj;
            return
          }
          let obj = {
            source: node.id,
            ShearerLoc: node.attrs.info.ShearerLoc,
            hierarchy: node.attrs.info.hierarchy
          };
          this.fixedTrack = obj;
        });
        this.fixedGraph.on('graph:mouseenter', ({
          e
        }) => {
          this.isTrack = false;
        });
        this.fixedGraph.on('graph:mouseleave', ({
          e
        }) => {
          this.isTrack = true;
        });
        this.fixedGraph.on('node:removed', e => {
          let index = e.index - 1;
          let tableItem = this.tableData[this.activeName].fixedList[this.tabValue]
          let temp = [tableItem[index].id]
          for (let i = 0; i < tableItem.length; i++) {
            let item = tableItem[i]
            let isCommit = temp.some(key => {
              return item.PreRunnerID == key
            })
            if (isCommit) {
              temp.push(item.id)
              item.isDelete = true
            }
          }
          tableItem.splice(index, 1)
          let i = tableItem.length;
          while (i--) {
            if (tableItem[i].isDelete) {
              tableItem.splice(i, 1);
            }
          }
          this.updateFixedMount()
        });
        this.fixedGraph.on("node:click", e => {
          this.fixedChangeNode(e);
        })
        this.fixedGraph.on('node:moved', e => {
          this.fixedChangeNode(e);
          this.fixedChangeNode(e);
        });
        this.fixedGraph.on('node:resized', e => {
          this.fixedChangeNode(e);
        });
      },
      fixedChangeNode(e) {
        this.isActionBlock = true
        let center = document.getElementById('fixedMount').scrollWidth / 2 - 4;
        let id = e.cell.id;
        console.log('id', id);
        let cell = initX6.getCell(id, this.fixedGraph);
        let step = 16
        let tableItem = this.tableData[this.activeName].fixedList
        for (let i = 0; i < tableItem[this.tabValue].items.length; i++) {
          let item = tableItem[this.tabValue].items[i]
          console.log(item);
          if (id == item.id) {
            let x = cell.position.x
            item.ActRegionL = x / step
            item.ActRegionH = (x + cell.size.width) / step
            this.form = item
            break
          }
        }
      },
      initFollow() {
        this.followGraph = initX6.initMount({
          node: 'followMount',
          height: 150
        });
        this.followGraph.on('node:click', e => {
          this.followChangNode(e);
        })
        this.followGraph.on('node:resized', e => {
          this.followChangNode(e);
        });
        this.followGraph.on('node:moved', e => {
          this.followChangNode(e);
        });
      },
      followChangNode(e) {
        this.isActionBlock = false;
        let center = document.getElementById('followMount').scrollWidth / 2;
        let list = this.tableData[this.activeName].actions;
        let id = e.cell.id;
        let cell = initX6.getCell(id, this.followGraph);
        for (let i = 0; i < list.length; i++) {
          if (id == list[i].STrackID) {
            let x = cell.position.x;
            let width = cell.size.width;
            let trigger = this.tableData[this.activeName].TriggerDir;
            if (trigger == 1) {
              console.log('x', x);
              if (list[i].ShearerDir == 1) {
                list[i]._SDLength = x - center - list[i].ShearerLoc * 1;
                list[i]._SDScope = list[i]._SDLength * 1 + width;
              }
              if (list[i].ShearerDir == 2) {
                list[i]._SDLength = center - (list[i].ShearerLoc * 1 + x + width);
                console.log(list[i]._SDLength);
                list[i]._SDScope = list[i]._SDLength * 1 + width;

              }
            }
            if (trigger == 2) {
              if (list[i].ShearerDir == 2) {
                list[i]._SDLength = x - center - list[i].ShearerLoc * 1;
                list[i]._SDScope = list[i]._SDLength * 1 + width;
              }
              if (list[i].ShearerDir == 1) {
                list[i]._SDLength = center - (list[i].ShearerLoc * 1 + x + width);
                list[i]._SDScope = list[i]._SDLength * 1 + width;
              }
            }
            this.form = list[i];
            InDB.actionsPool.put({
              ...list[i]
            })
            break;
          }
        }
      },
      initMountNode() {
        this.mountGraph = initX6.initMount({
          node: 'mountNode',
          scroll: true
        });
        this.mountGraph.on('graph:mouseenter', ({
          e
        }) => {
          this.isTrack = true;
        });
        this.mountGraph.on('graph:mouseleave', ({
          e
        }) => {
          this.isTrack = false;
        });
        this.mountGraph.on('node:mouseenter', ({
          node
        }) => {
          this.mountMouseenter(node);
        });
        this.mountGraph.on('node:mouseleave', ({
          node
        }) => {
          this.mountMouseleave(node);
        });
        this.mountGraph.on('node:removed', e => {
          let index = e.index;
          this.tableData[this.activeName].actions.splice(index, 1);
          this.updateMount();
        });
        this.mountGraph.on('node:click', e => {
          this.mountChangeNode(e);
        })
        this.mountGraph.on('node:resized', e => {
          this.mountChangeNode(e);
        });
        this.mountGraph.on('node:moved', e => {
          this.mountChangeNode(e);
        });
      },
      mountMouseleave(node) {
        if (node.id != 'mount') {
          node.removeTools();
        }
      },
      mountMouseenter(node) {
        if (node.id != 'mount') {
          node.addTools({
            name: 'button-remove',
            args: {
              x: 0,
              y: 0,
              offset: {
                x: 10,
                y: 10
              }
            }
          });
        }
      },
      mountChangeNode(e) {
        this.isActionBlock = false;
        let list = this.tableData[this.activeName].actions;
        let id = e.cell.id;
        let cell = initX6.getCell(id, this.mountGraph);
        let step = 5;
        for (let i = 0; i < list.length; i++) {
          if (id == list[i].STrackID) {
            list[i].ActRegionL = cell.position.x / step;
            list[i].ActRegionH = cell.size.width / step + cell.position.x / step;
            this.form = list[i];
            InDB.actionsPool.put({
              ...list[i]
            })
            break;
          }
        }
      },
      updateMount() {
        let mountList = formData.formDataMount(this.tableData[this.activeName].actions);
        this.mountGraph.fromJSON(mountList);
        let followList = formData.formDataFollow(this.tableData[this.activeName].actions, 'followMount', this.tableData[
          this.activeName].TriggerDir);
        this.followGraph.fromJSON(followList);
        InDB.CfgSTrackRunner.put({
          data: [...this.tableData],
          id: this.runnerData.CfgSTrackRunner_id
        })
      },
      updateFixedMount() {
        let list = formData.formDataFixed({
          list: this.fixedList[this.tabValue].items,
          trigger: this.tableData[this.activeName].TriggerDir
        });
        this.fixedGraph.fromJSON(list);
        let mount = this.fixedGraph.getCellById('mount')
        if (mount) {
          this.fixedGraph.scrollToCell(mount)
        }
        InDB.CfgSTrackRunner.put({
          data: [...this.tableData],
          id: this.runnerData.CfgSTrackRunner_id
        })
      },
    },
    created() {
      InDB.actionsPool.all().then((res) => {
        this.actions = res.map((item, i) => {
          let obj = {
            ...item,
            color: colors[i]
          };
          return obj;
        });
      })
      InDB.CfgSTrackControl.get(this.$route.query.id * 1).then(res => {
        this.runnerData = res
        if (this.runnerData.hasOwnProperty('CfgSTrackRunner_id')) {
          InDB.CfgSTrackRunner.get(this.runnerData.CfgSTrackRunner_id).then(res => {
            this.tableData = res.data
            this.fixedList = this.tableData[this.activeName].fixedList || []
            this.updateMount()
            this.updateFixedMount()
          })
        }
        if (!this.runnerData.hasOwnProperty('CfgSTrackRunner_id')) {
          InDB.STrackStages.all().then(res => {
            this.tableData = this.runnerData.StageIDs.map(item => {
              let obj = res.find(keys => {
                return keys.StageID == item
              })
              let obj2 = {
                ...obj,
                actions: [],
                collapseItems: [],
                fixedList: []
              }
              return obj2
            })
            InDB.CfgSTrackRunner.put({
              data: [...this.tableData]
            }).then(async (insertID) => {
              this.runnerData.CfgSTrackRunner_id = insertID
              InDB.CfgSTrackControl.put({
                ...this.runnerData
              })
              // let row=
            })
          })
        }
      })
    },
    mounted() {
      rule.initPlugin({
        el: 'ruler', //容器id
        startValue: 0,
        background: '#f5f5f5',
        success: function(res) {}
      });
      rule.initFixed({
        el: 'ruler2', //容器id
        startValue: 0,
        background: '#f5f5f5',
        success: function(res) {}
      });
      this.initMountNode();
      this.initFollow();
      this.initFixedMount();
    }

  };
</script>

<style scoped>
  .flex {
    display: flex;
  }

  .flex_wrap {
    flex-wrap: wrap;
  }

  .canvas_wrap {
    width: 100%;
    /* height: 600px; */
    /* overflow-y: scroll; */
  }

  .box-card+.box-card {
    margin-top: 8px;
  }

  .box-card /deep/ .el-form-item {
    margin-bottom: 4px !important;
  }

  .actions_item {
    padding: 5px 8px;
    border: #13c2c2 1px solid;
    border-radius: 20px;
    margin-bottom: 8px;
  }

  .actions_item+.actions_item {
    margin-left: 8px;
  }

  .actionsPool {
    width: calc(100% - 320px);
    position: fixed;
    bottom: 10px;
    z-index: 99;
  }

  .box-card /deep/ .g6-grid-container {
    z-index: 0 !important;
  }

  .ruler-wrap {
    width: 100%;
    overflow: hidden;
  }

  .bg_reginType {
    background-color: #0078d6;
  }
</style>
